package com.zmn.plat.admin.controller.orderconfig.orderstock.sp;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.VtDTO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.manager.common.database.annotation.ReadOnlyConnection;
import com.zmn.plat.common.dto.servcategory.ServCategoryDRO;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.entity.orderconfig.orderstock.channel.ChannelConfigClose;
import com.zmn.plat.model.entity.orderconfig.orderstock.sp.SpConfigClose;
import com.zmn.plat.model.entity.orderconfig.orderstock.sp.SpConfigCloseQuery;
import com.zmn.plat.model.entity.orderconfig.orderstock.sp.SpConfigQuery;
import com.zmn.plat.model.entity.orderconfig.orderstock.sp.SpConfigVO;

/**
 * 服务商库存配置
 *
 * @author tanghongjun
 * @since 2020年3月17日16:49:40
 */
@Controller
@RequestMapping("/plat/sp/config/")
public class SpOrderConfigListController extends SpOrderConfigBaseController {

    private Logger logger = LoggerFactory.getLogger(SpOrderConfigBaseController.class);

    /**
     * 描述: 列表
     *
     * @param query
     *            查询实体
     * @return ModelAndView
     */
    @SuppressWarnings("Duplicates")
    @RequestMapping(value = "list")
    @ReadOnlyConnection
    public ModelAndView list(@ModelAttribute SpConfigQuery query) {
        ModelAndView mav = new ModelAndView("orderconfig/orderstock/sp/list");
        if (Objects.isNull(query.getSpId())) {
            logger.error("服务商ID不能为空");
            return null;
        }

        // 城市集合
        List<VtDTO> cityList = baseCompanyAreaService.listVtByManageCompanyId(query.getSpId());
        List<SpConfigVO> items = spConfigBService.listVOPageByQuery(query);

        mav.addObject("items", items);
        mav.addObject("vo", query);
        mav.addObject("cityList", cityList);
        mav.addObject("servCategList", listServCategory());
        return mav;
    }

    /**
     * 描述: 批量设置
     *
     * @param spId
     *            查询实体
     * @return ModelAndView
     */
    @RequestMapping(value = "batchSet")
    @ReadOnlyConnection
    public ModelAndView batchSet(Integer spId) {
        ModelAndView mav = new ModelAndView("orderconfig/orderstock/sp/batchSet");
        // 城市集合
        List<VtDTO> cityList = baseCompanyAreaService.listVtByManageCompanyId(spId);
        mav.addObject("spId", spId);
        mav.addObject("cityList", cityList);
        return mav;
    }

    /**
     * 描述: 关闭库存页面
     *
     * @param configId
     *            查询实体
     * @return ModelAndView
     */
    @RequestMapping(value = "close")
    @ReadOnlyConnection
    public ModelAndView close(Integer configId) {
        ModelAndView mav = new ModelAndView("orderconfig/orderstock/dutyDate");
        super.dutyDate(mav);
        SpConfigCloseQuery query = new SpConfigCloseQuery();
        query.setStatus(GlobalConsts.NO);
        query.setCloseDayAfterOrEqCurrDay(true);
        query.setConfigId(configId);
        List<SpConfigClose> closeList = spConfigCloseService.listByQuery(query);
        List<LocalDate> closeDays = closeList.stream().map(item -> item.getDay().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
            .collect(Collectors.toList());
        Map<String, Object> data = new HashMap<>();
        data.put("configIds", Lists.newArrayList(configId));
        mav.addObject("closeDays", closeDays);
        mav.addObject("data", JSON.toJSONString(data));
        mav.addObject("submitURL", "/plat/sp/config/closeDays.action");
        return mav;
    }

    /**
     * 描述: 关闭库存页面
     *
     * @param configIds
     *            查询实体
     * @return ModelAndView
     */
    @RequestMapping(value = "batchClose")
    @ReadOnlyConnection
    public ModelAndView batchClose(String configIds) {
        ModelAndView mav = new ModelAndView("orderconfig/orderstock/dutyDate");
        super.dutyDate(mav);
        List<ChannelConfigClose> closeList = Collections.EMPTY_LIST;
        List<LocalDate> closeDays = closeList.stream().map(item -> item.getDay().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
            .collect(Collectors.toList());
        Map<String, Object> data = new HashMap<>();
        data.put("configIds", JSON.parseArray(configIds, Integer.class));
        mav.addObject("closeDays", closeDays);
        mav.addObject("data", JSON.toJSONString(data));
        mav.addObject("submitURL", "/plat/sp/config/closeDays.action");
        return mav;
    }

    /**
     * 描述: 开启库存页面
     *
     * @param configId
     *            查询实体
     * @return ModelAndView
     */
    @RequestMapping(value = "open")
    @ReadOnlyConnection
    public ModelAndView open(Integer configId) {
        ModelAndView mav = new ModelAndView("orderconfig/orderstock/open");
        SpConfigCloseQuery query = new SpConfigCloseQuery();
        query.setConfigId(configId);
        query.setStatus(GlobalConsts.NO);
        query.setCloseDayAfterOrEqCurrDay(true);
        List<SpConfigClose> closeList = spConfigCloseService.listByQuery(query);
        mav.addObject("closeList", closeList);
        mav.addObject("submitURL", "/plat/sp/config/openDays.action");
        return mav;
    }

    /**
     * 描述: 批量开启页面
     *
     * @param query
     *            查询实体
     * @return ModelAndView
     */
    @RequestMapping(value = "batchOpen")
    @ReadOnlyConnection
    public ModelAndView batchOpen(@ModelAttribute SpConfigQuery query) {
        ModelAndView mav = new ModelAndView("orderconfig/orderstock/batchOpen");

        Long todayTimestamp = DateUtil.getTodayTimestampMillis();
        List<SpConfigVO> items = spConfigBService.listVOPageByQuery(query).stream().map(item -> {
            return Optional.ofNullable(item.getSpConfigCloseList()).orElse(Collections.emptyList()).stream()
                .filter(day -> Objects.nonNull(day.getDay()) && day.getDay().getTime() >= todayTimestamp
                    && Objects.equals(day.getStatus(), GlobalConsts.NO))
                .map(day -> {
                    SpConfigVO closeDay = new SpConfigVO();
                    BeanUtils.copyProperties(item, closeDay);
                    closeDay.setId(day.getId());
                    closeDay.setDay(day.getDay());
                    return closeDay;
                });
        }).flatMap(item -> item).sorted(Comparator.comparing(SpConfigVO::getDay).reversed()).collect(Collectors.toList());

        mav.addObject("items", items);
        mav.addObject("query", query);
        mav.addObject("flag", "SP");
        mav.addObject("submitURL", "/plat/sp/config/openDays.action");
        return mav;
    }

    /**
     * 描述: 根据服务商ID获取开通的城市信息
     *
     * @param spId
     *            服务商ID
     * @return 服务商开通城市集合
     * @auther tanghongjun
     * @since 2020/3/20 10:26
     */
    @RequestMapping(value = "listCityBySpId")
    @ResponseBody
    @ReadOnlyConnection
    public ResponseDTO<List<VtDTO>> listCityBySpId(HttpServletResponse response,
        @RequestParam(value = "spId", defaultValue = "0") int spId) {
        if (NumberUtil.isNullOrZero(spId)) {
            return ResponseDTO.fail("服务商Id不能为空");
        }

        // 城市集合
        List<VtDTO> listResponseDTO = baseCompanyAreaService.listVtByManageCompanyId(spId);
        return ResponseDTO.success(listResponseDTO);
    }

    /**
     * 描述: 根据服务商ID和城市信息获取开通的服务分类
     *
     * @param spId
     *            服务商ID
     * @param cityId
     *            城市ID，可为空
     * @return 服务商开通城市集合
     * @auther tanghongjun
     * @since 2020/3/20 10:26
     */
    @RequestMapping(value = "listServCategBySpIdAndCity")
    @ResponseBody
    @ReadOnlyConnection
    public ResponseDTO<List<ServCategoryDRO>> listServCategBySpIdAndCity(HttpServletResponse response,
        @RequestParam(value = "spId", defaultValue = "0") int spId, @RequestParam(value = "cityId", defaultValue = "0") int cityId) {
        try {
            // 服务分类集合
            List<ServCategoryDRO> dros = manageCompanyAreaBService.listServCategByManageCompanyIdAndCityId(spId, cityId);
            return ResponseDTO.success(dros);
        } catch (PlatException ex) {
            return ResponseDTO.fail(ex.getMessage());
        }
    }

    /**
     * 描述: 根据服务商ID和城市信息、服务分类Id获取一级前台产品分类信息
     *
     * @param spId
     *            服务商ID
     * @param servCategId
     *            服务分类ID
     * @param cityId
     *            城市ID，可为空
     * @return 服务商开通城市集合
     * @auther tanghongjun
     * @since 2020/3/20 10:26
     */
    @RequestMapping(value = "listCategOneByManageCompanyIdAndServCategIdAndShowTypeAndCityId")
    @ResponseBody
    @ReadOnlyConnection
    public ResponseDTO<List<VtDTO>> listCategOneByManageCompanyIdAndServCategIdAndShowTypeAndCityId(HttpServletResponse response,
        @RequestParam(value = "spId", defaultValue = "0") int spId,
        @RequestParam(value = "servCategId", defaultValue = "0") int servCategId,
        @RequestParam(value = "cityId", defaultValue = "0") int cityId) {
        try {
            List<VtDTO> dtos = manageCompanyAreaBService.listCategOneByManageCompanyIdAndServCategIdAndShowTypeAndCityId(spId, servCategId,
                    cityId);
            return ResponseDTO.success(dtos);
        } catch (PlatException ex) {
            return ResponseDTO.fail(ex.getMessage());
        }

    }

    /**
     * 描述: 根据服务商ID和城市信息、服务分类Id、一级产品分类Id获取二级产品分类信息
     *
     * @param spId
     *            服务商ID
     * @param servCategId
     *            服务分类ID
     * @param categOneId
     *            产品一级分类ID
     * @param cityId
     *            城市ID，可为空
     * @return 服务商开通城市集合
     * @auther tanghongjun
     * @since 2020/3/20 10:26
     */
    @RequestMapping(value = "listCategTwoByManageCompanyIdAndServAndCategOneIdAndShowTypeAndCityId")
    @ResponseBody
    @ReadOnlyConnection
    public ResponseDTO<List<VtDTO>> listCategTwoByManageCompanyIdAndServAndCategOneIdAndShowTypeAndCityId(HttpServletResponse response,
        @RequestParam(value = "spId", defaultValue = "0") int spId,
        @RequestParam(value = "servCategId", defaultValue = "0") int servCategId,
        @RequestParam(value = "categOneId", defaultValue = "0") int categOneId,
        @RequestParam(value = "cityId", defaultValue = "0") int cityId) {
        try {
            List<VtDTO> dtos = manageCompanyAreaBService.listCategTwoByManageCompanyIdAndServAndCategOneIdAndShowTypeAndCityId(spId,
                servCategId, categOneId, cityId);
            return ResponseDTO.success(dtos);
        } catch (PlatException ex) {
            return ResponseDTO.fail(ex.getMessage());
        }
    }

    @RequestMapping(value = "listShowServCategory")
    @ResponseBody
    @ReadOnlyConnection
    public ResponseDTO<List<VtDTO>> listShowServCategory(HttpServletResponse response) {
        List<VtDTO> vts = listShowServCategory();
        return ResponseDTO.success(vts);
    }

    @RequestMapping(value = "listServCategory")
    @ResponseBody
    @ReadOnlyConnection
    public ResponseDTO<List<VtDTO>> listServCategory(HttpServletResponse response) {
        List<VtDTO> vts = listServCategory();
        return ResponseDTO.success(vts);
    }
}
